package com.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flower.domain.dto.LoginDto;
import com.flower.domain.dto.buyer.farmer.PageFarmerDto;
import com.flower.domain.entity.Farmer;
import com.flower.service.FarmerService;
import com.flower.mapper.FarmerMapper;
import com.flower.utils.Md5Util;
import com.flower.domain.vo.PageVO;
import com.flower.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author 86178
 * @description 针对表【farmer(花农信息表)】的数据库操作Service实现
 * @createDate 2025-02-17 20:54:03
 */
@Service
@Slf4j
public class FarmerServiceImpl extends ServiceImpl<FarmerMapper, Farmer>
        implements FarmerService {

    @Autowired
    private FarmerMapper farmerMapper;

    @Override
    public Farmer login(LoginDto loginDto) {
        // 根据用户名查询用户信息
        Farmer farmer = farmerMapper.selectOne(new QueryWrapper<Farmer>().eq("username", loginDto.getUsername()));
        // 判断用户是否存在
        if (farmer != null) {
            // 判断密码是否正确
            if (Md5Util.checkPassword(loginDto.getPassword(), farmer.getPassword())) {
                return farmer;
            }
        }
        return null;
    }

    @Override
    public PageVO<Farmer> pageList(PageFarmerDto pageFarmerDto) {
        // 构建查询条件
        LambdaQueryWrapper<Farmer> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加关键字搜索条件
        if (StringUtils.isNotBlank(pageFarmerDto.getKeyword())) {
            queryWrapper.like(Farmer::getUsername, pageFarmerDto.getKeyword())
                    .or()
                    .like(Farmer::getName, pageFarmerDto.getKeyword())
                    .or()
                    .like(Farmer::getTelephone, pageFarmerDto.getKeyword());
        }
        
        // 添加排序条件
        queryWrapper.orderByDesc(Farmer::getCreateTime);
        
        // 执行分页查询
        Page<Farmer> page = new Page<>(pageFarmerDto.getPageNumber(), pageFarmerDto.getPageSize());
        Page<Farmer> farmerPage = farmerMapper.selectPage(page, queryWrapper);
        
        // 构建返回结果
        PageVO<Farmer> pageVO = new PageVO<>();
        BeanUtils.copyProperties(farmerPage, pageVO);
        return pageVO;
    }

    @Override
    public Farmer findFarmerByEmail(String email) {
        // 根据邮箱查询用户信息
        return farmerMapper.selectOne(new QueryWrapper<Farmer>().eq("email", email));
    }

    @Override
    public Farmer getUserInfo() {
        // 获取当前登录用户ID
        Long userId = UserContext.getUserId();
        return farmerMapper.selectById(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(Farmer farmer) {
        farmerMapper.updateById(farmer);
    }

    @Override
    public Page<Farmer> getFarmerList(String keyword, Integer page, Integer size) {
        Page<Farmer> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Farmer> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(Farmer::getUsername, keyword)
                  .or()
                  .like(Farmer::getName, keyword)
                  .or()
                  .like(Farmer::getTelephone, keyword);
        }
        
        wrapper.orderByDesc(Farmer::getCreateTime);
        return this.page(pageParam, wrapper);
    }

    @Override
    public void addFarmer(Farmer farmer) {
        // 设置默认值
        farmer.setCreateTime(LocalDateTime.now());
        farmer.setUpdateTime(LocalDateTime.now());
        
        // 保存花农信息
        this.save(farmer);
    }

    @Override
    public void updateFarmer(Farmer farmer) {
        // 更新修改时间
        farmer.setUpdateTime(LocalDateTime.now());
        
        // 更新花农信息
        this.updateById(farmer);
    }

    @Override
    public void deleteFarmer(Integer id) {
        this.removeById(id);
    }

    @Override
    public Farmer getFarmerById(Integer id) {
        return this.getById(id);
    }

    @Override
    public boolean isUsernameExists(String username) {
        return isUsernameExists(username, null);
    }

    @Override
    public boolean isUsernameExists(String username, Integer excludeId) {
        LambdaQueryWrapper<Farmer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Farmer::getUsername, username);
        if (excludeId != null) {
            wrapper.ne(Farmer::getFarmerId, excludeId);
        }
        return this.count(wrapper) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(Integer userId, String role) {
        LambdaUpdateWrapper<Farmer> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Farmer::getFarmerId, userId)
                    .set(Farmer::getRole, role)
                    .set(Farmer::getUpdateTime, LocalDateTime.now());
        
        log.info("更新用户角色: userId={}, role={}", userId, role);
        return this.update(updateWrapper);
    }
}




